﻿using System;
using System.Collections.Generic;
using System.Linq;
using LINQtoCSV;
using Microsoft.VisualStudio.TestTools.LoadTesting;

namespace QA.TFS.Plugins.Load
{
    public class ConfigurationLoader<T> : ILoadTestPlugin where T : new()
    {

        #region ILoadTestPlugin Members

        private LoadTest _LoadTest;
        private string _FileName = string.Empty;

        public EventHandler<TestStartingEventArgs> TestStartingEvent;

        public string FileName
        {
            get { return _FileName; }
            set { _FileName = value; }
        }

        public void Initialize(LoadTest loadTest)
        {
            _LoadTest = loadTest;
            if (TestStartingEvent != null)
            {
                _LoadTest.TestStarting += TestStartingEvent;
                obtenerDatos();
            }
        }

        #endregion

        private void obtenerDatos()
        {
            CsvFileDescription inputFileDescription = new CsvFileDescription
            {
                SeparatorChar = ';',
                FirstLineHasColumnNames = true
            };

            CsvContext cc = new CsvContext();
            IEnumerable<T> datos = cc.Read<T>(FileName, inputFileDescription);
            SingletonDataAccess<T>.Instance.Datos = datos.ToList<T>();
        }

    }

    public class SingletonDataAccess<T>
    {

        private int index = 0;

        private List<T> datos = new List<T>();
        public List<T> Datos
        {
            set { datos = value; }
            get { return datos; }
        }

        private SingletonDataAccess() { }

        private static SingletonDataAccess<T> _Instance;

        public static SingletonDataAccess<T> Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new SingletonDataAccess<T>();
                return _Instance;
            }
        }

        public T Next()
        {
            if (datos.Count == index)
                index = 0;

            return datos[index++];
        }

    }


}
